package m4_routting;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");

        Channel c = f.newConnection().createChannel();

        //1.定义队列
        String rnd = UUID.randomUUID().toString();
        c.queueDeclare(rnd,false,true,true,null);
        //2.定义交换机
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        //3.输入绑定键进行绑定
        System.out.println("输入绑定键");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");
        for (String key : a) {
            c.queueBind(rnd,"direct_logs",key);
        }
        System.out.println("ok");
        //正常的消费数据
        //创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody());
                String key = delivery.getEnvelope().getRoutingKey();
                System.out.println("收到:"+msg+" - "+key);
                }
        };


        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        c.basicConsume(rnd,true,deliverCallback,cancelCallback);
    }
}
